package cn.yangjunda.multipart.commons;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import java.io.File;

/**
 * @author Juanda
 * @Description
 * @date 2017/12/19 9:22
 */
public abstract class CommonsFileUploadSupport {

    // 上传配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB

    private final DiskFileItemFactory fileItemFactory;

    private final ServletFileUpload fileUpload;

    public CommonsFileUploadSupport () {
        this.fileItemFactory = newFileItemFactory();
        this.fileUpload = newFileUpload(getFileItemFactory());
    }

    protected DiskFileItemFactory newFileItemFactory() {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        return factory;
    }

    protected abstract ServletFileUpload newFileUpload(DiskFileItemFactory fileItemFactory);

    protected ServletFileUpload prepareFileUpload() {
        ServletFileUpload fileUpload = getFileUpload();
        ServletFileUpload actualFileUpload = fileUpload;


        actualFileUpload = newFileUpload(getFileItemFactory());
        actualFileUpload.setSizeMax(fileUpload.getSizeMax());
        actualFileUpload.setFileSizeMax(fileUpload.getFileSizeMax());

        return actualFileUpload;
    }

    public DiskFileItemFactory getFileItemFactory() {
        return this.fileItemFactory;
    }

    public ServletFileUpload getFileUpload() {
        return fileUpload;
    }
}
